/**
 * 程序主界面
 * */
layui.define(["layer", "element", "globalConfig", "routes", "sysViews", "sdDialog", "sdLocal"], function(exports) {
    let layer = layui.layer;
    let element = layui.element;
    let globalConfig = layui.globalConfig;
    let sysViews = layui.sysViews;
    let sdDialog = layui.sdDialog;
    let sdLocal = layui.sdLocal;

    let routes = layui.routes;

    let a = ".layui-layout-admin>.layui-header";
    let n = ".layui-layout-admin>.layui-side>.layui-side-scroll";
    let i = ".layui-layout-admin>.layui-body";
    let m = i + ">.layui-tab";
    let r = i + ">.layui-body-header";
    let h = "admin-pagetabs";
    let o = "admin-side-nav";
    let c;
    let menus = [];
    let sysMain = {
        mTabPosition: undefined,
        mTabList: [],
        regRouter: function(v) {
            $.each(v, function(x, y) {
                if ((y.url).length > 0) {
                    y.url = '#'+y.url;
                    
                    let w = sysMain.getHashPath(y.url);
                    menus.push(y);
                    routes.reg(w, function(z) {
                        // 处理带参数url
                        path = globalConfig.viewPath + w + ".html?v=" + globalConfig.version; // new Date().getTime();
                        let view = {
                            menuId: z.href,
                            menuPath: path,
                            menuName: y.name
                        };
                        sysMain.loadView(view)                     
                    })
                }
                if (y.sub) {
                    sysMain.regRouter(y.sub)
                }
            })
            sdLocal.menus.put(menus);

        },
        loadView: function(x) {
            let B = x.menuId;
            let v = x.menuPath;
            let w = x.menuName;
            let D = sysMain.getHashPath("#" + B);
            let z = i + ">div[lay-id]";
            if (globalConfig.pageTabs) {
                let E;
                $(m + ">.layui-tab-title>li").each(function(G) {
                    if ($(this).attr("lay-id") == D) {
                        E = true;
                        return false
                    }
                });
                if (!E) {
                    if ((sysMain.mTabList.length + 1) >= globalConfig.maxTabNum) {
                        layer.msg("最多打开" + globalConfig.maxTabNum + "个选项卡", {
                            icon: 2
                        });
                        sysMain.go(sysMain.mTabPosition);
                        return
                    }
                    element.tabAdd(h, {
                        id: D,
                        title: '<span class="title">' + (w ? w : "") + "</span>",
                        content: '<div lay-id="' + D + '" lay-hash="' + B + '"></div>'
                    });
                    // (B != c) && sysMain.mTabList.push(x);
                    // 仅保留当前选择tab  sysMain.mTabList全部
                    (globalConfig.cacheTab) && sdLocal.putTempData("indexTabs", x)
                }
                z = m + '>.layui-tab-content>.layui-tab-item>div[lay-id="' + D + '"]';
                let C = $(z).attr("lay-hash");
                if (B != C) {
                    $(z).attr("lay-hash", B);
                    E = false;
                    for (let y = 0; y < sysMain.mTabList.length; y++) {
                        if (sysMain.mTabList[y].menuId == C) {
                            sysMain.mTabList[y] = x
                        }
                    }
                    // 仅保留当前选择tab  sysMain.mTabList全部
                    (globalConfig.cacheTab) && sdLocal.putTempData("indexTabs", x)
                }

                if (!E || routes.isRefresh) {
                    sysMain.renderView(v, z)
                }
                if (!x.noChange) {
                    element.tabChange(h, D)
                }
            } else {
                let F = $(z);
                if (!F || F.length <= 0) {
                    let A = '<div class="layui-body-header">';
                    A += '      <span class="layui-body-header-title"></span>';
                    A += '      <span class="layui-breadcrumb pull-right">';
                    A += '         <a href="#' + c + '">首页</a>';
                    A += "         <a><cite></cite></a>";
                    A += "      </span>";
                    A += "   </div>";
                    A += '   <div lay-id="' + B + '"></div>';
                    $(i).html(A);
                    element.render("breadcrumb")
                } else {
                    F.attr("lay-id", B)
                }
                if (c != B) {
                    sysMain.setTabTitle(w)
                } else {
                    sysMain.setTabTitle(undefined)
                }
                sysViews.activeNav(B);
                sysMain.mTabList.splice(0, sysMain.mTabList.length);
                // (c != B) && sysMain.mTabList.push(x);
                // 仅保留当前选择tab  sysMain.mTabList全部
                (globalConfig.cacheTab) && sdLocal.putTempData("indexTabs", x);
                sysMain.mTabPosition = B;
                sysMain.renderView(v, z)
            }
            (sysViews.getPageWidth() <= 750) && sysViews.flexible(true);
            $(".layui-table-tips-c").trigger("click")
        },
        renderView: function(w, x, y) {
            let v = $(x);
            !y && (y = v.parent());
            sdDialog.showLoading(y);
            try{
                v.load(w, function(response,status,xhr) {
                    if(status == 'success'){
                        setTimeout(function() {
                            sdDialog.removeLoading(y)
                        }, 150)
                    }else{
                        let noFound = 'components/common/404.html';
                        sdDialog.showLoading(y);
                        v.load(noFound, function () {
                            setTimeout(function() {
                                sdDialog.removeLoading(y)
                            }, 150)
                        })
                    }


                })
            }catch (e) {

            }

        },
        loadHome: function(y) {
            let A = y.url;
            let v = y.name;
            let z = sdLocal.getTempData("indexTabs");

            c = A.substring(1);
            sysMain.regRouter([y]);
            if (globalConfig.pageTabs) {
                let w = sysMain.getHashPath(A);
                path = globalConfig.viewPath + w + ".html?v=" + globalConfig.version; // new Date().getTime();
                sysMain.loadView({
                    menuId: c,
                    menuPath: path,
                    menuName: v,
                    noChange: true
                })
            }
            let x = (y.loadSetting == undefined ? true : y.loadSetting);
            if (x) {
                sysMain.loadSettings(z)
            }
            routes.init({
                index: c,
                notFound: function(B) {
                    globalConfig.routerNotFound && globalConfig.routerNotFound(B)
                }
            })
        },
        go: function(v) {
            routes.go(v)
        },
        getHashPath: function(y) {

            let v = layui.router(y);
            let x = "";
            for (let w = 0; w < v.path.length; w++) {
                x += ("/" + v.path[w])
            }
            return x
        },
        setTabTitle: function(w, v) {
            if (!globalConfig.pageTabs) {
                if (w) {
                    $(r).addClass("show");
                    let x = $(r + ">.layui-body-header-title");
                    x.html(w);
                    x.next(".layui-breadcrumb").find("cite").last().html(w)
                } else {
                    $(r).removeClass("show")
                }
            } else {
                w || (w = "");
                v || (v = sysMain.getHashPath());
                v && $(m + '>.layui-tab-title>li[lay-id="' + v + '"] .title').html(w)
            }
        },
        getViewSuffix: function(w) {
            let v;
            
            if (typeof globalConfig.viewSuffix === "string") {
                v = globalConfig.viewSuffix
            } else {
                v = globalConfig.viewSuffix(w)
            }
            
            if (globalConfig.version != undefined) {
                if (w.indexOf("?") == -1) {
                    v += "?v="
                } else {
                   
                    v += "&v="
                }
                if (globalConfig.version == true) {
                    v += new Date().getTime()
                } else {
                    v += globalConfig.version
                }
            }
            return v
        },
        loadSettings: function(y) {
            if (globalConfig.cacheTab) {
                let z = y;
                if (z) {
                    for (let w = 0; w < z.length; w++) {
                        if (globalConfig.pageTabs) {
                            z[w].noChange = true;
                            sysMain.loadView(z[w])
                        }
                    }
                }
            }
            let v = layui.data(globalConfig.localCacheKey);
            if (v) {
                let x = v.openFooter;
                if (x != undefined && x == false) {
                    $("body.layui-layout-body").addClass("close-footer")
                }
                if (v.naletrow != undefined) {
                    $(n + ">.layui-nav-tree").removeClass("arrow2 arrow3");
                    v.naletrow && $(n + ">.layui-nav-tree").addClass(v.naletrow)
                }
            }
        }
    };
    let j = layui.data(globalConfig.localCacheKey);
    if (j) {
        // let p = j.openTab;
        // if (p != undefined) {
        //     globalConfig.pageTabs = p
        // }
        globalConfig.pageTabs = true;
    }
    let f = ".layui-layout-admin .site-mobile-shade";
    if ($(f).length <= 0) {
        $(".layui-layout-admin").append('<div class="site-mobile-shade"></div>')
    }
    $(f).click(function() {
        sysViews.flexible(true)
    });
  
    if (globalConfig.pageTabs && $(m).length <= 0) {
        let e = '<div class="layui-tab" lay-allowClose="true" lay-filter="admin-pagetabs">';
        e += '       <ul class="layui-tab-title"></ul>';
        e += '      <div class="layui-tab-content"></div>';
        e += "   </div>";
        e += '   <div class="layui-icon admin-tabs-control layui-icon-prev" click-event="leftPage"></div>';
        e += '   <div class="layui-icon admin-tabs-control layui-icon-next" click-event="rightPage"></div>';
        e += '   <div class="layui-icon admin-tabs-control layui-icon-down">';
        e += '      <ul class="layui-nav admin-tabs-select" lay-filter="admin-pagetabs-nav">';
        e += '         <li class="layui-nav-item" lay-unselect>';
        e += "            <a></a>";
        e += '            <dl class="layui-nav-child layui-anim-fadein">';
        e += '               <dd click-event="closeThisTabs" lay-unselect><a>关闭当前标签页</a></dd>';
        e += '               <dd click-event="closeOtherTabs" lay-unselect><a>关闭其它标签页</a></dd>';
        e += '               <dd click-event="closeAllTabs" lay-unselect><a>关闭全部标签页</a></dd>';
        e += "            </dl>";
        e += "         </li>";
        e += "      </ul>";
        e += "   </div>";
        $(i).html(e);
        element.render("nav")
    }
    element.on("nav(" + o + ")", function(w) {
        let v = $(w);
        if ("true" == $(n + ">.layui-nav-tree").attr("lay-accordion")) {
            if (v.parent().hasClass("layui-nav-itemed") || v.parent().hasClass("layui-this")) {
                $(n + ">.layui-nav .layui-nav-itemed").not(v.parents(".layui-nav-child").parent()).removeClass("layui-nav-itemed");
                v.parent().addClass("layui-nav-itemed")
            }
            v.trigger("mouseenter")
        }
        sysViews.setNavHoverCss(v.parentsUntil(".layui-nav-item").parent().children().eq(0))
    });
    element.on("tab(" + h + ")", function(w) {
        let v = $(this).attr("lay-id");
        let x = $(m + '>.layui-tab-content>.layui-tab-item>div[lay-id="' + v + '"]').attr("lay-hash");
        sysMain.mTabPosition = x;
        sysViews.activeNav(x);
        sysMain.go(x);
        sysViews.resizeTable(0);
        sysViews.rollPage("auto")
    });
    element.on("tabDelete(" + h + ")", function(w) {
        let v = sysMain.mTabList[w.index - 1];
        if (v) {
            sysMain.mTabList.splice(w.index - 1, 1);
            (globalConfig.cacheTab) && sdLocal.putTempData("indexTabs", sysMain.mTabList)
        }
        if ($(m + ">.layui-tab-title>li.layui-this").length <= 0) {
            $(m + ">.layui-tab-title>li:last").trigger("click")
        }
    });
    $("body").off("clicapp.navMore").on("clicapp.navMore", "[nav-bind]", function() {
        let v = $(this).attr("nav-bind");
        $('ul[lay-filter="' + o + '"]').addClass("layui-hide");
        $('ul[nav-id="' + v + '"]').removeClass("layui-hide");
        if (sysViews.getPageWidth() <= 750) {
            sysViews.flexible(false)
        }
        $(a + ">.layui-nav .layui-nav-item").removeClass("layui-this");
        $(this).parent(".layui-nav-item").addClass("layui-this")
    });
    if (globalConfig.openTabCtxMenu && globalConfig.pageTabs) {
        $(m + ">.layui-tab-title").off("contextmenu.tab").on("contextmenu.tab", "li", function(w) {
            let v = $(this).attr("lay-id");
            context.show([{
                icon: "layui-icon layui-icon-refresh",
                name: "刷新当前",
                click: function() {
                    element.tabChange(h, v);
                    sysViews.refresh(sysMain.getHashPath("#" + v))
                }
            }, {
                icon: "layui-icon layui-icon-close-fill ctx-ic-lg",
                name: "关闭当前",
                click: function() {
                    sysViews.closeThisTabs(v)
                }
            }, {
                icon: "layui-icon layui-icon-unlink",
                name: "关闭其他",
                click: function() {
                    sysViews.closeOtherTabs(v)
                }
            }, {
                icon: "layui-icon layui-icon-close ctx-ic-lg",
                name: "关闭全部",
                click: function() {
                    sysViews.closeAllTabs()
                }
            }], w.clientX, w.clientY);
            return false
        })
    }
    exports("sysMain", sysMain)
});
